import Vue from "vue";
import Vuex from "vuex";
import { getUerInfo } from "../request/api";
import { router } from "../main";
import MainApp from "../main";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    Authorization: localStorage.getItem("Authorization") || null, //token
    authenticateStatus: localStorage.getItem("authenticateStatus") || null, //用户认证信息
    userMobile: localStorage.getItem("userMobile") || null, //用户手机号
    isChina: localStorage.getItem("isChina") || null, //判断是否为国内的手机号，+86且为国内11位手机号
    userId: localStorage.getItem("userId") || null, //用户id
    userName: localStorage.getItem("userName") || null, //用户名称
    email: localStorage.getItem("userName") || null, //用户邮箱
    curriculumId: localStorage.getItem("curriculumId") || null, //用户简历id
    USER_INFO: {}, //用户信息,
    messageObj: {},
  },
  mutations: {
    setAuthorization(state, value) {
      //设置token
      state.Authorization = value;
      localStorage.setItem("Authorization", value);
    },
    setisChina(state, value) {
      //设置是否为国内的手机号
      state.isChina = value;
      localStorage.setItem("isChina", value);
    },
    setUserMobile(state, value) {
      //设置登录手机号
      state.userMobile = value;
      localStorage.setItem("userMobile", value);
    },
    setUserId(state, value) {
      //设置用户id
      state.userId = value;
      localStorage.setItem("userId", value);
    },
    setCurriculumId(state, value) {
      //设置用户简历id
      state.curriculumId = value;
      localStorage.setItem("curriculumId", value);
    },
    SET_USER_INFO(state, value) {
      //修改用户信息
      state.USER_INFO = value;
      state.userName = value.nickname || "";
      state.email = value.email || "";
      state.authenticateStatus = value.status || "";
      state.userMobile = value.mobile || "";
      localStorage.setItem("userName", value.nickname);
      localStorage.setItem("email", value.email);
      localStorage.setItem("authenticateStatus", value.status);
      localStorage.setItem("userMobile", value.mobile);
    },
    loginOut(state, fn) {
      //退出账号
      window.localStorage.clear();
      for (let k in state) {
        state[k] = null;
      }
      fn && fn();
    },
    setMessageObj(state, value) {
      //设置未读消息
      state.messageObj = value;
    },
  },
  actions: {
    async FETCH_USER_INFO_WX({ commit }, payload) {
      console.log('SET_USER_INFO', payload)
      const { mobile, redirectUrl, next, urlparams } = payload // 跳转的参数
      if (!mobile) {
        return;
      }
      getUerInfo({ mobile }).then((res) => {
        if (res.data) {
          commit("setUserId", res.data.id);
          commit("SET_USER_INFO", res.data);
          commit("setisChina", true)
          if (res.data.nickname == '') {
            router.push({ name: "userInformation"});
          } else if (redirectUrl) {
            // 设置用户信息后，跳转到想跳转的地方
            // 如果参数不为空
            if (JSON.stringify(urlparams) !== '{}') {
              const resultParams = decodeURIComponent(urlparams)
              next({
                path: redirectUrl,
                ...resultParams
              })
              return
            }
            next(redirectUrl)
          } else {
            next && next()
          }
        } else if (res.data === null) {
          commit("loginOut");
          // 退出登录，默认可以访问首页
          if (
            MainApp.$route.path !== "/" &&
            MainApp.$router.path !== "/iframePage"
          ) {
            router.replace({ name: "login" });
          }
        }
      });
    },
    async FETCH_USER_INFO(
      { commit },
      params = { mobile: this.state.userMobile,  }
    ) {
      if (!this.state.userMobile) {
        return;
      }
      getUerInfo(params).then((res) => {
        if (res.data) {
            const {redirectUrl} = params
          commit("setUserId", res.data.id);
          commit("SET_USER_INFO", res.data);
          if (res.data.nickname == '') { // 未完成初步个人信息注册，还在游客模式
            if (redirectUrl) {
                router.push({ name: "userInformation", query: {redirectUrl: redirectUrl }});
            } else {
                router.push({ name: "userInformation", query: {redirectUrl: encodeURIComponent(window.location.href)} });
            }
          }
        } else if (res.data === null) {
          commit("loginOut");
          // 退出登录，默认可以访问首页
          if (
            MainApp.$route.path !== "/" &&
            MainApp.$router.path !== "/iframePage"
          ) {
            router.replace({ name: "login" });
          }
        }
      });
    },
  },
  modules: {},
});
